package cn.edu.ncu.housinghub.service.impl;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.dto.request.maintenance.MaintenanceRequest;
import cn.edu.ncu.housinghub.entity.maintance.Maintenance;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.entity.house.House;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.mapper.MaintenanceMapper;
import cn.edu.ncu.housinghub.service.MaintenanceService;
import cn.edu.ncu.housinghub.utils.common.TokenUtil;
import cn.edu.ncu.housinghub.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 维修服务实现类
 */
@Service
public class MaintenanceServiceImpl implements MaintenanceService {
    
    @Autowired
    private MaintenanceMapper maintenanceMapper;
    
    @Override
    public Result applyMaintenance(MaintenanceRequest request, String token) {
        try {
            // 获取当前用户信息
            User currentUser = TokenUtil.getUserByToken(token);
            if (currentUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }
            
            // 验证用户是否有权限对该房源申请维修（需要是该房源的租客）
            boolean hasPermission = maintenanceMapper.checkTenantPermission(currentUser.getId(), request.getHouseId());
            if (!hasPermission) {
                throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
            }
            
            // 创建维修申请
            Maintenance maintenance = new Maintenance();
            maintenance.setUser(currentUser);
            
            House house = new House();
            house.setHouseId(request.getHouseId());
            maintenance.setHouse(house);
            
            maintenance.setFaultDescription(request.getFaultDescription());
            maintenance.setMaintenanceStatus(0); // 0=待处理
            maintenance.setCreateTime(LocalDateTime.now());
            
            // 处理故障照片
            if (request.getFaultPhotos() != null && !request.getFaultPhotos().isEmpty()) {
                maintenance.setFaultPhoto(String.join(",", request.getFaultPhotos()));
            }
            
            // 插入维修申请
            int result = maintenanceMapper.insertMaintenance(maintenance);
            if (result > 0) {
                return Result.success(maintenance.getMaintenanceId());
            } else {
                throw new BusinessException(ErrorCodeConstant.APPLY_ERROR);
            }
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "维修申请提交失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result getTenantMaintenanceList(String token) {
        try {
            User currentUser = TokenUtil.getUserByToken(token);
            if (currentUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }
            
            List<Maintenance> maintenanceList = maintenanceMapper.selectByTenantId(currentUser.getId());
            return Result.success(maintenanceList);
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.USER_QUERY_ERROR, "获取维修申请列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result getLandlordMaintenanceList(String token) {
        try {
            User currentUser = TokenUtil.getUserByToken(token);
            if (currentUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }
            
            // 验证用户是否为房东
            if (!currentUser.getRole().equals(SystemConstant.ROLE_LANDLORD.getIntegerValue())) {
                throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
            }
            
            List<Maintenance> maintenanceList = maintenanceMapper.selectByLandlordId(currentUser.getId());
            return Result.success(maintenanceList);
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.USER_QUERY_ERROR, "获取维修申请列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result handleMaintenance(Long maintenanceId, Integer status, String remark, String token) {
        try {
            User currentUser = TokenUtil.getUserByToken(token);
            if (currentUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }
            
            // 验证用户是否为房东
            if (!currentUser.getRole().equals(SystemConstant.ROLE_LANDLORD.getIntegerValue())) {
                throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
            }
            
            // 验证房东是否有权限处理该维修申请
            boolean hasPermission = maintenanceMapper.checkLandlordPermission(currentUser.getId(), maintenanceId);
            if (!hasPermission) {
                throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
            }
            
            // 更新维修申请状态
            int result = maintenanceMapper.updateMaintenanceStatus(maintenanceId, status, remark);
            if (result > 0) {
                return Result.success("维修申请处理成功");
            } else {
                throw new BusinessException(ErrorCodeConstant.APPLY_ERROR);
            }
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.APPLY_ERROR, "维修申请处理失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result getMaintenanceDetail(Long maintenanceId, String token) {
        try {
            User currentUser = TokenUtil.getUserByToken(token);
            if (currentUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }
            
            Maintenance maintenance = maintenanceMapper.selectById(maintenanceId);
            if (maintenance == null) {
                throw new BusinessException(ErrorCodeConstant.USER_QUERY_ERROR, "维修申请不存在");
            }
            
            // 验证用户是否有权限查看该维修申请（租客或房东）
            boolean hasPermission = maintenance.getUser().getId().equals(currentUser.getId()) ||
                                  maintenanceMapper.checkLandlordPermission(currentUser.getId(), maintenanceId);
            if (!hasPermission) {
                throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
            }

            return Result.success(maintenance);
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.USER_QUERY_ERROR, "获取维修申请详情失败：" + e.getMessage());
        }
    }
}
